package com.lzk.basic.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class EmailUtils {
    @Autowired
    private  static JavaMailSender javaMailSender;

    /**
     * 简单版的邮件发送
     * @param from 发送人
     * @param subject 主题
     * @param text 内容
     * @param to 接收人
     */
    public  static void simpleEmail(String from,String subject,String text,String to){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom(from);
        //邮件主题
        mailMessage.setSubject(subject);
        //邮件内容：普通文件无法解析html标签
        mailMessage.setText(text);
        //收件人
        mailMessage.setTo(to);
        //发送邮件
        javaMailSender.send(mailMessage);
    }

    public static void mimeEmail(String from,String subject,String text,String Attachment,String to) throws MessagingException {
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom(from);
        helper.setSubject(subject);
        // texe = "<h1>你的店铺已经注册!!!</h1><img src='http://123.207.27.208/group1/M00/00/B9/rBE3kWD_fEuALou2AAB4rV4bI7c231.jpg' ><a href='http://localhost:8080/shop/active/22'>点击该链接激活</a>"
        helper.setText(text,true);
        //添加附件
        // \是转义符 所以需要\\
        String fileName = Attachment.substring(Attachment.lastIndexOf('\\'+1));
        helper.addAttachment(fileName,new File(Attachment));
        //收件人
        helper.setTo(to);
        javaMailSender.send(mimeMessage);
    }

}
